<template>
  <view class="my-container">
    <!-- 用户信息卡片 -->
    <view class="user-card" @click="checkLoginAndAction">
      <image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
      <view class="user-info">
        <text class="username">{{ userInfo.username || '未登录用户' }}</text>
        <text class="extra-info" v-if="userInfo.email">{{ userInfo.email }}</text>
        <text class="extra-info" v-else>{{ isLoggedIn ? '点击完善个人信息' : '点击登录账号' }}</text>
      </view>
      <uni-icons type="forward" size="20" color="#999"></uni-icons>
    </view>

    <!-- 登录/退出按钮 -->
    <view class="auth-btn" :class="{ 'logout-btn': isLoggedIn }" @click="isLoggedIn ? handleLogout() : handleLogin()">
      <text>{{ isLoggedIn ? '退出登录' : '立即登录' }}</text>
    </view>

    <!-- 功能模块 -->
    <view class="function-modules">
      <!-- 浏览历史 -->
      <view class="module-card">
        <view class="module-header" @click="goToHistory">
          <text class="title">浏览历史</text>
          <uni-icons type="forward" size="16" color="#999"></uni-icons>
        </view>
        <scroll-view class="history-list" scroll-x v-if="historyBooks.length > 0">
          <view 
            class="history-item" 
            v-for="item in historyBooks" 
            :key="item.bookId"
            @click="goToDetail(item.bookId)"
          >
            <image class="cover" :src="item.cover || '/static/屏幕截图 2025-06-22 200009.png'" mode="aspectFill" />
            <text class="book-name">{{ item.bookName }}</text>
          </view>
          <view class="history-more" v-if="historyBooks.length > 3" @click="goToHistory">
            <text>查看更多</text>
            <uni-icons type="forward" size="14" color="#999"></uni-icons>
          </view>
        </scroll-view>
      </view>

      <!-- 收藏书架 -->
      <view class="module-card">
        <view class="module-header" @click="goToFavorites">
          <text class="title">收藏书架</text>
          <uni-icons type="forward" size="16" color="#999"></uni-icons>
        </view>
        <view class="favorites-grid" v-if="favoriteBooks.length > 0">
          <view 
            class="favorite-item" 
            v-for="item in favoriteBooks.slice(0, 4)" 
            :key="item.bookId"
            @click="goToDetail(item.bookId)"
          >
            <image class="cover" :src="item.cover || '/static/屏幕截图 2025-06-22 200009.png'" mode="aspectFill" />
            <text class="book-name">{{ item.bookName }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        username: '',
        email: '',
        avatar: ''
      },
      historyBooks: [],
      favoriteBooks: [],
      isLoggedIn: false
    }
  },
  onShow() {
    this.checkLoginStatus();
    this.loadHistory();
    this.loadFavorites();
  },
  methods: {
    checkLoginStatus() {
      try {
        const savedUser = uni.getStorageSync('userInfo');
        if (savedUser) {
          this.userInfo = {
            username: savedUser.username || '',
            email: savedUser.email || '',
            avatar: savedUser.avatar || '/static/images/default-avatar.png'
          };
          this.isLoggedIn = true;
        } else {
          this.userInfo = {
            username: '',
            email: '',
            avatar: '/static/images/default-avatar.png'
          };
          this.isLoggedIn = false;
        }
      } catch (e) {
        console.error('读取用户信息失败:', e);
        this.userInfo = {
          username: '',
          email: '',
          avatar: '/static/images/default-avatar.png'
        };
        this.isLoggedIn = false;
      }
    },
    loadHistory() {
      const history = uni.getStorageSync('historyBooks') || [];
      this.historyBooks = history.reverse();
    },
    loadFavorites() {
      const favorites = uni.getStorageSync('favoriteBooks') || [];
      this.favoriteBooks = favorites;
    },
    checkLoginAndAction() {
      if (!this.isLoggedIn) {
        this.handleLogin();
      } else {
        this.editUserInfo();
      }
    },
    editUserInfo() {
      uni.navigateTo({
        url: '/pages/My_editUser/My_editUser',
        events: {
          acceptUpdatedInfo: (data) => {
            this.userInfo = data;
            uni.setStorageSync('userInfo', data);
          }
        },
        success: (res) => {
          res.eventChannel.on('acceptUpdatedInfo', (data) => {
            this.userInfo = data;
            uni.setStorageSync('userInfo', data);
          });
        }
      });
    },
    handleLogin() {
      uni.navigateTo({
        url: '/pages/login/login',
        events: {
          acceptUserInfo: (data) => {
            this.userInfo = data;
            this.isLoggedIn = true;
            uni.setStorageSync('userInfo', data);
          }
        },
        success: (res) => {
          res.eventChannel.on('acceptUserInfo', (data) => {
            this.userInfo = data;
            this.isLoggedIn = true;
            uni.setStorageSync('userInfo', data);
          });
        }
      });
    },
    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除所有相关存储
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('historyBooks');
            uni.removeStorageSync('favoriteBooks');
            
            // 重置数据
            this.isLoggedIn = false;
            this.userInfo = {
              username: '',
              email: '',
              avatar: '/static/images/default-avatar.png'
            };
            this.historyBooks = [];
            this.favoriteBooks = [];
            
            // 显示提示
            uni.showToast({
              title: '已退出登录',
              icon: 'success',
              complete: () => {
                // 跳转到登录页面
                uni.reLaunch({
                  url: '/pages/login/login'
                });
              }
            });
          }
        }
      });
    },
    goToHistory() {
      uni.navigateTo({
        url: '/pages/My_history/My_history'
      });
    },
    goToFavorites() {
      uni.navigateTo({
        url: '/pages/My_loves/My_loves'
      });
    },
    goToDetail(bookId) {
      uni.navigateTo({
        url: `/pages/bookdetail/bookdetail?id=${bookId}`
      });
    }
  }
}
</script>

<style>
/* 页面容器 */
.my-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 用户信息卡片 */
.user-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
  background-color: #f0f0f0;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.extra-info {
  font-size: 28rpx;
  color: #999;
}

/* 登录/退出按钮 */
.auth-btn {
  background-color: #fff;
  color: #1989fa;
  text-align: center;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  font-size: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.logout-btn {
  color: #f56c6c;
}

/* 功能模块 */
.function-modules {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.module-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 浏览历史列表 */
.history-list {
  display: flex;
  white-space: nowrap;
  padding-bottom: 10rpx;
}

.history-item {
  display: inline-flex;
  flex-direction: column;
  width: 160rpx;
  margin-right: 20rpx;
}

.history-item .cover {
  width: 160rpx;
  height: 220rpx;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
}

.history-item .book-name {
  font-size: 26rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-more {
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 160rpx;
  height: 220rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  color: #999;
  font-size: 26rpx;
}

/* 收藏书架 */
.favorites-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.favorite-item {
  display: flex;
  flex-direction: column;
}

.favorite-item .cover {
  width: 100%;
  height: 200rpx;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
}

.favorite-item .book-name {
  font-size: 26rpx;
  color: #333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

/* 空状态提示 */
.empty-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>